package com.guoxue.action.front.pay;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.guoxue.action.front.BaseAction;
import com.guoxue.domain.CoinsVo;
import com.guoxue.domain.RechargeVo;
import com.guoxue.domain.UserCoinsVo;
import com.guoxue.pay.alipay.config.AlipayConfig;
import com.guoxue.pay.alipay.config.ClientConfig;
import com.guoxue.pay.alipay.util.MyAliPay;
import com.guoxue.service.ICoinsService;
import com.guoxue.service.IRechargeService;
import com.guoxue.service.IUserCoinsService;
import com.guoxue.util.JsonUtil;
import com.guoxue.util.OtherUtils;

@Controller
@RequestMapping(value = "/pay")
public class AliPayAction extends BaseAction {

	@Resource
	private IRechargeService rechargeService;
	@Resource
	private IUserCoinsService userCoinsService;
	@Resource
	private ICoinsService coinsService;
	/**
	 * 
	 * @param req
	 * @param resp
	 * @param coinsId 金币id
	 * @param count 数量
	 * @param uid 用户id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getOrderInfo")
	public JSON getOrderInfo(HttpServletRequest req, HttpServletResponse resp, Integer coinsId, Integer count,Integer uid) {
		try {
			if (coinsId == null) {
				return Message(ERROR, "未提交商品id", null);
			}
			if (count == null) {
				return Message(ERROR, "未提交商品数量", null);
			}
			if(count <= 0){
				return Message(ERROR, "商品数量不能小于等于0", null);
			}
			if(count > 1 ){
				return Message(ERROR, "商品数量超过限制数量", null);
			}
			if (null == uid) {
				return Message(ERROR, "未提交用户id", null);
			}
			CoinsVo coinsVo = coinsService.getCoinsById(coinsId);
			if(null == coinsVo){
				return Message(ERROR, "该商品不存在", null);
			}
			Integer price = coinsVo.getPrice();
			RechargeVo recharge = new RechargeVo();
			recharge.setCoinsId(coinsId);
			recharge.setCount(count);
			recharge.setuId(uid);
			int money = count * price;
			recharge.setPayMoney(money);
			recharge.setPayStatus("1");
			recharge.setPayWay("1");
			String aa = OtherUtils.getCurrentDateNum();
		    int bb = (new Random().nextInt(9999-1000+1)+1000);
			String outTradeNo = aa+bb;
			recharge.setOutTradeNo(outTradeNo);
			recharge.setCreateTime(OtherUtils.getCurrentDate());
			rechargeService.saveRecharge(recharge);
			Map<String, String> sPara = new HashMap<String, String>();
			JSONObject json = new JSONObject();
			System.out.println(outTradeNo);
			json.put("out_trade_no", outTradeNo);
			json.put("subject", "1");
			json.put("payment_type", "1");
			json.put("total_amount", "0.01");
			//json.put("total_amount", (float)money);
			json.put("body", "订单说明");
			json.put("timeout_express", "30m");
			json.put("seller_id", AlipayConfig.partner);
			json.put("product_code", "QUICK_MSECURITY_PAY");
			sPara = MyAliPay.buildOrderParamMap(ClientConfig.APP_ID, json.toString(), OtherUtils.getCurrentDate().toString(), AlipayConfig.return_url);
			String orderUrl = MyAliPay.buildOrderParam(sPara);
			String sign = MyAliPay.getSign(sPara, AlipayConfig.private_keys);
			String signOrderUrl = orderUrl+"&"+sign;
			System.out.println(signOrderUrl);
			return Message(SUCCESS, "订单创建成功", signOrderUrl);

		} catch (Exception e) {
			e.printStackTrace();
			return Message(ERROR, "订单创建失败", null);
		}
	}
	
	
	
	
	@ResponseBody
	@RequestMapping(value = "/callBackAliPay")
	public JSON callBackAliPay(HttpServletRequest req, HttpServletResponse resp) {
		try {
			Map<String, String> params = new HashMap<String, String>();
			Map requestParams = req.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				System.out.println(">>>>>参数" + name + ":" + valueStr);
				params.put(name, valueStr);
			}
			requestParams.get("trade_status");
			String out_trade_no = req.getParameter("out_trade_no");
			String tradeNo = req.getParameter("trade_no");
			String tradeStatus = req.getParameter("trade_status");
			String sign = (String) params.get("sign");
			String seller_id = params.get("seller_id");
			String app_id = params.get("app_id");
			String total_amount = params.get("total_amount");
			String content = AlipaySignature.getSignCheckContentV2(params);
			//if (AlipaySignature.rsaCheckContent(content, sign, AlipayConfig.public_keys, AlipayConfig.input_charset)) {// 验证成功
				if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
					System.out.println(">>>>>状态要更新了");
					// 商品交易成功之后的业务逻辑代码
					//1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
					//2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
					//3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
					//4、验证app_id是否为该商户本身。上述1、2、3、4有任何一个验证不通过，则表明同步校验结果是无效的，只有全部验证通过后，才可以认定买家付款成功
					System.out.println(">>>>>下单成功" + tradeNo);
					//1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
					RechargeVo recharge = rechargeService.getRecharge(out_trade_no);
					if(null == recharge){
						resp.getWriter().append("failure");
						return Message(ERROR, "支付失败", null);
					}
					System.out.println("AliPay:"+recharge.getPayStatus().equals("1"));
					System.out.println("AliPay:"+recharge.getPayStatus().equals(1));
					if(recharge.getPayStatus().equals("1")){
						//2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
						Integer payMoney = recharge.getPayMoney();
						System.out.println("aliPay支付金额"+payMoney);
						System.out.println("payMoney"+payMoney);
						System.out.println("seller_id"+seller_id);
						/*if(!payMoney.equals(total_amount)){
							resp.getWriter().append("failure");
							return Message(ERROR, "支付失败", null);
						}*/
						//3、校验通知中的seller_id
						/*if(!seller_id.equals(AlipayConfig.partner)){
							resp.getWriter().append("failure");
							return Message(ERROR, "支付失败", null);
						}*/
						//4、验证app_id是否为该商户本身
						/*if(!app_id.equals(ClientConfig.APP_ID)){
							resp.getWriter().append("failure");
							return Message(ERROR, "支付失败", null);
						}*/
						recharge.setPayStatus("2");
						recharge.setTradeNo(tradeNo);
						rechargeService.saveRecharge(recharge);
						System.out.println("更新订单状态和加入支付宝订单号");
						UserCoinsVo userCoinsVo = userCoinsService.getUserCoinsById(recharge.getuId());
						if(null == userCoinsVo){
							userCoinsVo = new UserCoinsVo();
							userCoinsVo.setUid(recharge.getuId());
							CoinsVo coinsVo = coinsService.getCoinsById(recharge.getCoinsId());
							System.out.println("aliPay增加前金币无记录"+userCoinsVo.getCoinsNumber());
							Integer coinsNumber = coinsVo.getValue() * recharge.getCount()+coinsVo.getGiveCoins();
							System.out.println("aliPay增加金币无记录"+coinsNumber);
							userCoinsVo.setCoinsNumber(coinsNumber);
							System.out.println("aliPay增加后金币无记录"+userCoinsVo.getCoinsNumber());
							userCoinsService.saveUserCoins(userCoinsVo);
						}else{
							CoinsVo coinsVo = coinsService.getCoinsById(recharge.getCoinsId());
							System.out.println("aliPay增加前金币有记录"+userCoinsVo.getCoinsNumber());
							Integer coinsNumber = coinsVo.getValue() * recharge.getCount()+coinsVo.getGiveCoins();
							System.out.println("aliPay增加金币有记录"+coinsNumber);
							userCoinsVo.setCoinsNumber(userCoinsVo.getCoinsNumber()+coinsNumber);
							System.out.println("aliPay增加后金币有记录"+userCoinsVo.getCoinsNumber());
							userCoinsService.saveUserCoins(userCoinsVo);
						}
						System.out.println("aliPay更新用户金币数量");
						resp.getWriter().append("success");
						return Message(SUCCESS, "支付成功", null);
					}else{
						resp.getWriter().append("failure");
						return Message(ERROR, "支付失败", null);
					}
				}else{
					resp.getWriter().append("failure");
					return Message(ERROR, "支付失败", null);
				}
			/*} else {// 验证失败
				System.out.println(">>>>>验签失败" + tradeNo);
				System.out.println(">>>>>交易被关闭了");
				return Message(ERROR, "支付失败", null);
			}*/

		} catch (Exception e) {
			e.printStackTrace();
			return Message(ERROR, "支付失败", null);
		}
	}

}
